﻿using DearlerPlatfrom.Common;
using DearlerPlatfrom.Common.TokenModule;
using DearlerPlatfrom.Service.CustomerApp;
using DearlerPlatfrom.Service.CustomerAppDto;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DearlerPlatfrom.Web.Controllers
{
   
    [ApiController]
    public class LoginControllers : ControllerBase
    {
        private readonly ICustomerService _customerService;
        private readonly IConfiguration _configuration;

        public LoginControllers(ICustomerService customerService, IConfiguration configuration)
        {
            _customerService = customerService;
            _configuration = configuration;
        }

        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="customerDto"></param>
        /// <returns></returns>
        [HttpPost,Route("Login")]
        public async Task<string> CheckLogin(CustomerLoginDto customerDto)
        {
            if (string.IsNullOrWhiteSpace(customerDto.PassWord) || string.IsNullOrWhiteSpace(customerDto.CustomerNo))
            {
                HttpContext.Response.StatusCode = 403;
                return default;
            }
            var res = await _customerService.CheckPassword(customerDto);
            if (!res)
            {
                HttpContext.Response.StatusCode = 403;
                return "NoUser";
            }
            var customer = await _customerService.GetCustomerAsync(customerDto.CustomerNo);
            return GetToken(customer.Id, customer.CustomerNo, customer.CustomerName);
        }

        /// <summary>
        /// 生成Token返回
        /// </summary>
        /// <returns></returns>
        private string GetToken(int CustomerId, string CustomerNo, string CustomerName)
        {
            var token = _configuration.GetSection("Jwt").Get<JwtTokenModel>();
            token.Id = CustomerId;
            token.CustomerNo = CustomerNo;
            token.CustomerName = CustomerName;
            return TokenHelper.CreateToken(token);
        }
    }
}
